package cn.wolfcode.shop.cloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class ErrorResponseJSONFilter extends ZuulFilter {
    @Value("${error.path:/error}")
    private String errorPath;

    public ErrorResponseJSONFilter() {
    }

    public String filterType() {
        return "error";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    @SneakyThrows
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = context.getResponse();
        Map<String, Object> map = new HashMap<>();
        if ("true".equals(context.get("rateLimitExceeded"))) {
            //刷新频繁
            map.put("code", "429");
            map.put("msg", "操作频繁");
        } else {
            map.put("code", 500);
            map.put("msg", "系统繁忙");
        }
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(map));
        context.setSendZuulResponse(false);
        return null;
    }
}
